package com.example.springboot159.filter;


import com.example.springboot159.wrapper.RequestWrapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class RequestBodyFilter implements Filter {
    private static  final Logger logger = LoggerFactory.getLogger(RequestBodyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWraper = null;
        if (request instanceof HttpServletRequest) {
            String contentType = request.getContentType();
            if (StringUtils.isNotBlank(contentType) && contentType.toLowerCase().contains("application/json")) {
                logger.info("---- request body filter----");
                requestWraper = new RequestWrapper((HttpServletRequest) request);
            }
        }

        if (requestWraper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWraper, response);
        }
    }

    @Override
    public void destroy() {

    }
}
